package bb.lanxing.activity.base;

import static android.content.Intent.URI_INTENT_SCHEME;
import static android.webkit.WebSettings.LOAD_NO_CACHE;

import java.io.File;
import java.lang.ref.WeakReference;
import java.net.MalformedURLException;
import java.net.URL;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.animation.DecelerateInterpolator;
import android.webkit.CookieManager;
import android.webkit.DownloadListener;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;

import bb.lanxing.R;
import bb.lanxing.common.config.Constants;
import bb.lanxing.model.database.BiciCookie;
import bb.lanxing.network.MyHttpClient;
import bb.lanxing.service.DownloadService;
import bb.lanxing.util.AppFileUtils;
import bb.lanxing.view.BiciAlertDialogBuilder;
import gov.nist.core.Separators;

public class WebBaseActivity extends BaseActivity {
    private static final int FILE_CHOOSER_RESULT_CODE = 17;
    private static final int MSG_UPDATE_PROGRESS = 1;
    private static final int MSG_UPDATE_SECOND_PROGRESS = 2;
    private static final String TAG = "WebBaseActivity";
    protected boolean shareable;
    protected UIHandler uiHandler;
    protected String webUrl;
    protected String token;
    protected boolean toolbarable = true;
    protected boolean homeBackable = true;
    protected DownloadListener downloadListener = (str, str2, str3, str4, j) -> {
        Log.i(TAG, "onDownloadStart: url = " + str + ", contentDisposition=" + str3 + ", mimetype=" + str4
                + ", contentLength=" + j + ", " + "userAgent=" + str2);
        final String substring = str.substring(str.lastIndexOf("/") + 1);
        new BiciAlertDialogBuilder(WebBaseActivity.this).setTitle(R.string.dialog_prompt)
                .setMessage(WebBaseActivity.this.getString(R.string.web_download_dialog_msg, substring,
                        j > 0 ? Formatter.formatFileSize(WebBaseActivity.this.getApplicationContext(), j)
                                : WebBaseActivity.this.getString(R.string.web_download_dialog_unknown_size)))
                .setNegativeButton(R.string.cancel, null)
                .setPositiveButton(R.string.ok,
                        (dialogInterface, i) -> DownloadService.download(WebBaseActivity.this.getApplicationContext(),
                                str,
                                AppFileUtils.getNoRepeatFilePath(
                                        AppFileUtils.buildExternalDirectoryPath("download") + File.separator + substring),
                                false))
                .show();
    };
    TextView closeView;
    ProgressBar progressBar;
    MenuItem reprtMenuItem;
    MenuItem shareMenuItem;
    Toolbar toolbar;
    WebView webView;
    private Animator.AnimatorListener goOnListener;
    private boolean isNeedReport;
    private boolean isNoNeedShare;
    private View mToolbarPageClose;
    private ObjectAnimator progressAnim;
    private ValueCallback uploadMessage;
    private ValueCallback uploadMessageAboveL;

    protected int getContentLayoutRes() {
        return R.layout.activity_webview;
    }

    protected boolean onHitTestResult(WebView.HitTestResult hitTestResult) {
        return false;
    }

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(getContentLayoutRes());
        bindView(getWindow().getDecorView());
        setupActionBar(true);
        this.isNeedReport = getIntent().getBooleanExtra("isNeedReport", false);
        this.isNoNeedShare = getIntent().getBooleanExtra("isNoNeedShare", false);
        this.webUrl = getIntent().getStringExtra("web_url");
        this.shareable = getIntent().getBooleanExtra("can_share", true);
        this.toolbarable = getIntent().getBooleanExtra("can_toolbar", true);
        this.homeBackable = getIntent().getBooleanExtra("homeBackable", true);

        this.token = getIntent().getStringExtra("token");

        if (!this.toolbarable) {
            this.toolbar.setVisibility(View.GONE);
        }
        String title = this.webView.getTitle();
        if (TextUtils.isEmpty(title)) {
            title = getIntent().getStringExtra("title");
            if (TextUtils.isEmpty(title)) {
                title = "蓝行";
            }
        }
        setTitle(title);
        this.uiHandler = new UIHandler(this);
        WebView webView = this.webView;
        if (webView != null) {
            webView.clearCache(true);
            this.webView.setDownloadListener(this.downloadListener);
            WebSettings settings = this.webView.getSettings();
            settings.setDomStorageEnabled(true);
            settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
            settings.setCacheMode(LOAD_NO_CACHE);
            settings.setMixedContentMode(0);
            settings.setJavaScriptEnabled(true);
            settings.setSaveFormData(true);
            settings.setPluginState(WebSettings.PluginState.ON);
            String trim = settings.getUserAgentString().trim();
            settings.setUserAgentString(trim + " lanxing/3.20.4");
            syncCookies(this.webUrl);
            initListeners();
        }
    }

    private void initCookies(String str) {
        try {
            BiciCookie byName = BiciCookie.getByName(MyHttpClient.CLIENT_COOKIE_NAME);
            if (byName == null || byName.getName().isEmpty() || byName.getValue().isEmpty()) {
                return;
            }
            String str2 = null;
            try {
                str2 = new URL(str).getHost();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            String str3 = byName.getName() + Separators.EQUALS + byName.getValue() + ";domain=" + str2;
            Log.d(TAG, "strCookie = " + str3);
            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setAcceptCookie(true);
            cookieManager.setCookie(str2, str3);
            CookieManager.getInstance().flush();
        } catch (Exception e2) {
            e2.printStackTrace();
        }
    }

    private void syncCookies(String str) {
        if (str != null) {
            if (str.contains(MyHttpClient.DOMAIN_BASE) || str.contains(Constants.DOMAIN_HEAT)) {
                initCookies(str);
            }
        }
    }

    public void toggleShareBtn(boolean z, Drawable drawable) {
        MenuItem menuItem = this.shareMenuItem;
        if (menuItem != null) {
            menuItem.setVisible(z);
            if (drawable != null) {
                this.shareMenuItem.setIcon(drawable);
            }
        }
    }

    protected void toggleShareBtn(boolean z) {
        toggleShareBtn(z, null);
    }

    public void toggleShareBtn(String str) {
        if (bb.lanxing.util.text.TextUtils.isEmptyOrNull(str)) {
            toggleShareBtn(this.shareable);
        } else {
            toggleShareBtn("true".equals(str));
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (this.isNeedReport) {
            getMenuInflater().inflate(R.menu.segment_report, menu);
            this.shareMenuItem = menu.findItem(R.id.segment_detail_share);
            MenuItem findItem = menu.findItem(R.id.reportBtn);
            this.reprtMenuItem = findItem;
            findItem.setVisible(true);
            this.reprtMenuItem.setOnMenuItemClickListener(menuItem -> {
                WebBaseActivity webBaseActivity = WebBaseActivity.this;
                webBaseActivity.reportDialog(webBaseActivity);
                return true;
            });
            this.shareMenuItem.setVisible(false);
        } else {
            getMenuInflater().inflate(R.menu.menu_share, menu);
            MenuItem findItem2 = menu.findItem(R.id.action_share);
            this.shareMenuItem = findItem2;
            findItem2.setVisible(false);
        }
        if (this.isNoNeedShare) {
            this.shareMenuItem = null;
        }
        return super.onCreateOptionsMenu(menu);
    }

    private void pageClose() {
        ActivityCompat.finishAfterTransition(this);
    }

    @Override
    public boolean onHomeBack() {
        WebView webView = this.webView;
        if (webView != null && webView.canGoBack()) {
            this.webView.goBack();
            return true;
        }
        return super.onHomeBack();
    }

    @Override
    public void onBackPressed() {
        WebView webView = this.webView;
        if (webView != null && webView.canGoBack()) {
            this.webView.goBack();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.uiHandler.removeCallbacksAndMessages(null);
        WebView webView = this.webView;
        if (webView != null) {
            webView.removeAllViews();
            try {
                this.webView.clearFormData();
                this.webView.clearHistory();
                ViewParent parent = this.webView.getParent();
                if (parent != null) {
                    ((ViewGroup) parent).removeView(this.webView);
                }
                this.webView.destroy();
            } catch (Exception e) {
                e.printStackTrace();
            }
            this.webView = null;
        }
    }

    private void initListeners() {
        this.webView.setOnLongClickListener(
                view -> WebBaseActivity.this.onHitTestResult(WebBaseActivity.this.webView.getHitTestResult()));
    }

    public void animToProgress(final int i, final boolean z) {
        ObjectAnimator objectAnimator = this.progressAnim;
        if (objectAnimator != null && objectAnimator.isRunning()) {
            Animator.AnimatorListener animatorListener = this.goOnListener;
            if (animatorListener != null) {
                this.progressAnim.removeListener(animatorListener);
            }
            AnimatorListenerAdapter animatorListenerAdapter = new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animator) {
                    super.onAnimationEnd(animator);
                    WebBaseActivity.this.uiHandler.removeMessages(MSG_UPDATE_SECOND_PROGRESS);
                    WebBaseActivity.this.uiHandler.obtainMessage(MSG_UPDATE_SECOND_PROGRESS, i, z ? 1 : 0)
                            .sendToTarget();
                }
            };
            this.goOnListener = animatorListenerAdapter;
            this.progressAnim.addListener(animatorListenerAdapter);
            return;
        }
        this.progressAnim = ObjectAnimator.ofInt(this.progressBar, "secondaryProgress",
                        this.progressBar.getSecondaryProgress(), i).setDuration(400L);
        Log.i(TAG, "animToProgress: end = " + z + " progress = " + i);
        this.progressAnim.setInterpolator(new DecelerateInterpolator());
        if (z) {
            Animator.AnimatorListener animatorListener2 = this.goOnListener;
            if (animatorListener2 != null) {
                this.progressAnim.removeListener(animatorListener2);
                this.goOnListener = null;
            }
            this.progressAnim.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animator) {
                    super.onAnimationEnd(animator);
                    WebBaseActivity.this.progressBar.setVisibility(View.GONE);
                    Log.i(TAG, "onAnimationEnd: " + i);
                }
            });
        }
        this.progressAnim.start();
    }

    private void bindView(View view) {
        this.webView = view.findViewById(R.id.webView);
        this.progressBar = view.findViewById(R.id.web_progress);
        this.toolbar = view.findViewById(R.id.toolbar);
        this.closeView = view.findViewById(R.id.toolbar_title_left);
        this.mToolbarPageClose = view.findViewById(R.id.toolbar_title_left);
        this.mToolbarPageClose.setOnClickListener(v -> pageClose());
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FILE_CHOOSER_RESULT_CODE) {
            if (this.uploadMessage == null && this.uploadMessageAboveL == null) {
                return;
            }
            Uri data2 = (data == null || resultCode != -Activity.RESULT_OK) ? null : data.getData();
            if (this.uploadMessageAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
                return;
            }
            if (uploadMessage != null) {
                uploadMessage.onReceiveValue(data2);
                this.uploadMessage = null;
            }
        }
    }

    private void onActivityResultAboveL(int requestCode, int resultCode, Intent intent) {
        Uri[] uriArr;
        if (requestCode != FILE_CHOOSER_RESULT_CODE || this.uploadMessageAboveL == null) {
            return;
        }
        if (resultCode != -1 || intent == null) {
            uriArr = null;
        } else {
            String dataString = intent.getDataString();
            ClipData clipData = intent.getClipData();
            if (clipData != null) {
                uriArr = new Uri[clipData.getItemCount()];
                for (int i = 0; i < clipData.getItemCount(); i++) {
                    uriArr[i] = clipData.getItemAt(i).getUri();
                }
            } else {
                uriArr = null;
            }
            if (dataString != null) {
                uriArr = new Uri[] { Uri.parse(dataString) };
            }
        }
        this.uploadMessageAboveL.onReceiveValue(uriArr);
        this.uploadMessageAboveL = null;
    }

    public void reportDialog(Context context) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setMessage(getString(R.string.dialog_message_report_person));
        builder.setTitle(getString(R.string.dialog_title_report));
        builder.setPositiveButton(context.getString(R.string.ok), (dialogInterface, i) -> {
            Toast.makeText(WebBaseActivity.this, R.string.toast_message_report_segment, Toast.LENGTH_SHORT).show();
            dialogInterface.dismiss();
        });
        builder.setNegativeButton(context.getString(R.string.str_sync_cancel),
                (dialogInterface, i) -> dialogInterface.dismiss());
        builder.create().show();
    }

    public static class UIHandler extends Handler {
        private WeakReference<WebBaseActivity> reference;

        public UIHandler(WebBaseActivity webBaseActivity) {
            this.reference = new WeakReference<>(webBaseActivity);
        }

        @Override
        public void handleMessage(Message message) {
            WebBaseActivity webBaseActivity = this.reference.get();
            if (webBaseActivity == null) {
                return;
            }
            int i = message.what;
            int i2 = 0;
            if (i == MSG_UPDATE_PROGRESS) {
                if (webBaseActivity.progressBar == null
                        || webBaseActivity.progressBar.getVisibility() != View.VISIBLE) {
                    return;
                }
                int progress = webBaseActivity.progressBar.getProgress();
                int secondaryProgress = webBaseActivity.progressBar.getSecondaryProgress();
                if (secondaryProgress <= progress
                        || (progress = progress + (secondaryProgress / 10)) < secondaryProgress) {
                    i2 = progress;
                }
                webBaseActivity.progressBar.setProgress(i2);
                sendMessageDelayed(obtainMessage(MSG_UPDATE_PROGRESS), 80L);
            } else if (i == MSG_UPDATE_SECOND_PROGRESS && webBaseActivity.progressBar != null
                    && webBaseActivity.progressBar.getVisibility() == View.VISIBLE
                    && webBaseActivity.progressBar.getSecondaryProgress() < message.arg1) {
                webBaseActivity.animToProgress(message.arg1, message.arg2 != 0);
            }
        }
    }

    protected class BaseWebChromeClient extends WebChromeClient {
        public BaseWebChromeClient() {

        }

        @Override
        public void onProgressChanged(WebView webView, int i) {
            super.onProgressChanged(webView, i);
            if (WebBaseActivity.this.progressBar != null
                    && WebBaseActivity.this.progressBar.getVisibility() == View.VISIBLE && i > 0 && i < 100) {
                WebBaseActivity.this.animToProgress(i, false);
            }
        }

        @Override
        public void onReceivedTitle(WebView webView, String str) {
            super.onReceivedTitle(webView, str);
            Log.v(TAG, "onReceivedTitle: " + str);
            if (TextUtils.isEmpty(str)) {
                return;
            }
            WebBaseActivity.this.setTitle(str);
        }

        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> valueCallback,
                FileChooserParams fileChooserParams) {
            WebBaseActivity.this.uploadMessageAboveL = valueCallback;
            openImageChooserActivity(fileChooserParams.getAcceptTypes());
            return true;
        }

        private void openImageChooserActivity(String... strArr) {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            if (strArr != null && strArr.length > 0) {
                String str = strArr[0];
                for (int i = 1; i < strArr.length; i++) {
                    if (!TextUtils.isEmpty(strArr[i])) {
                        str = str + ";" + strArr[i];
                    }
                }
                String replaceAll = TextUtils.isEmpty(str) ? "*/*" : str.replaceAll(",", ";");
                intent.setType(replaceAll);
                Log.i(TAG, "accept types = " + replaceAll);
            }
            WebBaseActivity.this.startActivityForResult(Intent.createChooser(intent, "请选择"), FILE_CHOOSER_RESULT_CODE);
        }
    }

    protected class BaseWebViewClient extends WebViewClient {
        public BaseWebViewClient() {
        }

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView webView, WebResourceRequest webResourceRequest) {
            return super.shouldInterceptRequest(webView, webResourceRequest);
        }

        @Override
        public void onPageStarted(WebView webView, String str, Bitmap bitmap) {
            super.onPageStarted(webView, str, bitmap);
            Log.v(TAG, "onPageStarted: " + str);
            Log.v(TAG, "onPageStarted: title = " + WebBaseActivity.this.webView.getTitle());
            if (WebBaseActivity.this.webView != null && !TextUtils.isEmpty(WebBaseActivity.this.webView.getTitle())) {
                WebBaseActivity webBaseActivity = WebBaseActivity.this;
                webBaseActivity.setTitle(webBaseActivity.webView.getTitle());
            }
            if (WebBaseActivity.this.progressBar != null) {
                WebBaseActivity.this.progressBar.setProgress(0);
                WebBaseActivity.this.progressBar.setSecondaryProgress(0);
                if (WebBaseActivity.this.progressBar.getVisibility() != View.VISIBLE) {
                    WebBaseActivity.this.progressBar.setVisibility(View.VISIBLE);
                    WebBaseActivity.this.uiHandler.obtainMessage(1).sendToTarget();
                }
            }
        }

        @Override
        public void onPageFinished(WebView webView, String str) {
            super.onPageFinished(webView, str);
            Log.v(TAG, "onPageFinished: " + str);
            Log.v(TAG, "onPageFinished: title = " + WebBaseActivity.this.webView.getTitle());
            if (!TextUtils.isEmpty(WebBaseActivity.this.webView.getTitle())) {
                WebBaseActivity webBaseActivity = WebBaseActivity.this;
                webBaseActivity.setTitle(webBaseActivity.webView.getTitle());
            }
            if (WebBaseActivity.this.progressBar == null
                    || WebBaseActivity.this.progressBar.getVisibility() != View.VISIBLE) {
                return;
            }
            WebBaseActivity.this.animToProgress(100, true);
            WebBaseActivity.this.uiHandler.removeMessages(1);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView webView, WebResourceRequest webResourceRequest) {
            return shouldOverrideUrlLoading(webView, webResourceRequest.getUrl().toString());
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView webView, String str) {
            Log.v(TAG, "shouldOverrideUrlLoading: " + str);
            if (str.startsWith("http:") || str.startsWith("https:")) {
                return false;
            }
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse(str));
            if (intent.resolveActivity(WebBaseActivity.this.getPackageManager()) != null) {
                try {
                    WebBaseActivity.this.startActivity(intent);
                    return true;
                } catch (SecurityException e) {
                    e.printStackTrace();
                }
            }
            try {
                if (str.startsWith("alipays://platformapi/startApp?") || str.startsWith("weixin://wap/pay?")) {
                    Intent intent2 = new Intent();
                    intent2.setAction(Intent.ACTION_VIEW);
                    intent2.setData(Uri.parse(str));
                    WebBaseActivity.this.startActivity(intent2);
                } else if (str.contains("platformapi/startapp")) {
                    Intent parseUri = Intent.parseUri(str, URI_INTENT_SCHEME);
                    parseUri.addCategory(Intent.CATEGORY_BROWSABLE);
                    parseUri.setComponent(null);
                    WebBaseActivity.this.startActivity(parseUri);
                    return true;
                } else if (str.contains("platformapi") && str.contains("startapp")) {
                    Intent parseUri2 = Intent.parseUri(str, URI_INTENT_SCHEME);
                    parseUri2.addCategory(Intent.CATEGORY_BROWSABLE);
                    parseUri2.setComponent(null);
                    WebBaseActivity.this.startActivity(parseUri2);
                    return true;
                } else if (str.contains("download")) {
                    WebBaseActivity.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(str)));
                    return true;
                } else {
                    webView.loadUrl(str);
                }
            } catch (Exception unused) {
            }
            return true;
        }
    }
}